<?php

namespace catchAdmin\customs\controller;

use catchAdmin\customs\excel\orderExport;
use catchAdmin\customs\excel\orderGoodsExport;
use catchAdmin\customs\excel\clearOrderExport;
use catchAdmin\customs\excel\clearOrderGoodsExport;
use catchAdmin\customs\excel\clearFinishOrderExport;
use catchAdmin\customs\excel\clearFinishOrderGoodsExport;
use catcher\base\CatchRequest as Request;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\customs\model\Order as OrderModel;
use catchAdmin\customs\model\OrderSon as OrderSonModel;
use catcher\library\excel\Excel;
use catcher\library\excel\reader\Reader;
use catcher\Utils;
use think\Response;
use think\response\Json;
use think\facade\Db;
use catcher\Code;

class Order extends CatchController
{

    protected $orderModel;
    protected $OrderSonModel;

    /**
     *
     * @time 2021/11/03 14:02
     * @param OrderModel $orderModel
     * @param OrderSonModel $OrderSonModel
     * @return mixed
     */
    public function __construct(OrderModel $orderModel, OrderSonModel $OrderSonModel)
    {
        $this->orderModel = $orderModel;
        $this->OrderSonModel = $OrderSonModel;
    }

    /**
     * 订单列表
     *
     * @time 2020年01月09日
     * @param CatchRequest $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(): \think\response\Json
    {
        return CatchResponse::paginate($this->orderModel->getList());
    }

    /**
     * 清单列表
     *
     * @time 2020年01月09日
     * @param CatchRequest $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function clearList(): \think\response\Json
    {
        return CatchResponse::paginate($this->orderModel->getClearList());
    }
    /**
     * 清关（放行）列表
     *
     * @time 2020年01月09日
     * @param CatchRequest $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function finishClearList(): \think\response\Json
    {
        return CatchResponse::paginate($this->orderModel->getFinishClearList());
    }


    /**
     *
     * @time 2021/11/03 14:02
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        // return CatchResponse::success($this->orderModel->storeBy($request->post()));
        return CatchResponse::fail('未申明的类型');
    }

    /**
     *
     * @time 2021/11/03 14:02
     * @param $id
     * @return Response
     */
    public function read($id): Response
    {
        // return CatchResponse::paginate($this->orderModel->getList());
        // return CatchResponse::success($this->orderModel->findBy($id));
        return CatchResponse::fail('未申明的类型');
    }

    public function joinList(): \think\response\Json
    {
        return CatchResponse::paginate($this->orderModel->getJoinList());
    }

    /**
     *
     * @time 2021/11/03 14:02
     * 修改进口业务申报订单
     * @param Request $request
     * @return Json
     */
    public function edit(Request $request): Response
    {
        $type = $request->post('type');
        if (!$type) {
            return CatchResponse::fail('缺少参数');
        }
        if ($type === 1) {
            $orderId = $request->post('orderId');
            if (!$orderId) {
                return CatchResponse::fail('缺少参数');
            }
            //订单表
            $orderInfo = OrderModel::field('id,orderId,amount,distributionfee,tax,realPayment,contactAddr,detailAddr,contactName,payOrderNo,buyerName,ConsigneeCode,contactMobile,ebpCode,ebpName,paycomCode,paycomName,discount,logistics_status,push_order,push_inventory,error_msg,customs_port,returnInfo,clear_returnInfo,invt_no,orderDate,postcode,task_no,modifyTime,waybill_status,bill_no,express_no,express_company,currency,note,copNo')->where(array('orderId' => $orderId))->find()->toArray();
            $orderInfo['ConsigneeCode'] = preg_replace('/(\w{8})\w*(\w{4})/','$1******$2',$orderInfo['ConsigneeCode']);


            if (!$orderInfo) {
                return CatchResponse::fail('没有该订单');
            }
            //订单子表
            $orderInfo['goodsListStr'] = OrderSonModel::field('id,orderId,RecordMaterialNo,goods_name,barcode,num,spec_qty,price')
                ->where(['orderId'=>$orderInfo['orderId'],'deleteStatus'=>0])
                ->select()
                ->each(function (&$item){
                    $where['deleted_at'] = 0;
                    $where['barcode'] = $item['barcode'];
                    if(!empty($item['RecordMaterialNo'])){
                        $where['record_material_no'] = $item['RecordMaterialNo'];
                    }
                    $material_info = Db::name('db_customs_record_material')->field('net_weight,gross_weight,origin_country_code,trade_country_code,currency_code,g_code,g_model,g_name,currency_code,unit,unit1,unit2,qty1,qty2,record_material_no')->where($where)->find();
                    if ($material_info){
                        foreach ($material_info as $key => $value){
                            $item[$key] = $value;
                        }
                    }
                })
                ->toArray();
            if (!$orderInfo['goodsListStr']) {
                return CatchResponse::fail('该订单,没有商品信息');
            }
            return CatchResponse::success($orderInfo, '查询成功');
        } elseif ($type === 2) {
            $form = $request->post('form');
            if (!$form) {
                return CatchResponse::fail('缺少参数');
            }
            $info = json_decode(json_encode($form), true);

            //处理身份证 身份证前端展示6个*  存在*表示未作更改
            if(array_key_exists('ConsigneeCode',$info)&&strstr($info['ConsigneeCode'],"****")){
                unset($info['ConsigneeCode']);
            }
            $OrderSonModel = 0;
            foreach ($info['goodsListStr'] as $key => $value) {
                //以下为账册信息  不允许在此修改
                unset($value['net_weight']);
                unset($value['gross_weight']);
                unset($value['trade_country_code']);
                unset($value['origin_country_code']);
                unset($value['g_model']);
                unset($value['g_name']);
                unset($value['currency_code']);
                unset($value['unit']);
                unset($value['unit1']);
                unset($value['unit2']);
                unset($value['unit2']);
                unset($value['qty1']);
                unset($value['qty2']);
                unset($value['record_material_no']);
                unset($value['g_code']);
                $OrderSonModel += Db::name('db_customs_orderlist')->save($value);
            }
            unset($info['goodsListStr']);
            $orderModel = Db::name('db_customs_order')->save($info);
            if ($OrderSonModel > 0 || $orderModel > 0) {
                return CatchResponse::success([], '编辑成功');
            } else {
                return CatchResponse::fail('编辑失败');
            }
        } else {
            return CatchResponse::fail('未申明的类型');
        }
    }

    /**
     *
     * @time 2021/11/03 14:02
     * @param $id
     * @return Response
     */
    public function delete(Request $request): Response
    {
        $orderId = $request->post('orderId');
        if (!$orderId) {
            return CatchResponse::fail('缺少参数orderId');
        }
        // 启动事务
        Db::startTrans();
        try {

            $res = Db::table('db_customs_order')
                ->where(['orderId' => $orderId])
                ->save(['status' => 1, 'deleteStatus' => 1, 'modifyTime' => date('Y-m-d H:i:s')]);

            $res1 = Db::table('db_customs_orderlist')
                ->where(['orderId' => $orderId])
                ->save(['deleteStatus' => 1]);

            if ($res && $res1) {
                Db::commit();
                return CatchResponse::success([], '删除成功');

            } else {
                Db::rollback();
                return CatchResponse::fail('删除失败');

            }

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return CatchResponse::fail($e->getMessage());

        }
    }

    /**
     *
     * @time 2021/11/03 14:02
     * 进口业务申报订单
     * @param Request $request
     * @return Json
     */
    public function test(Request $request)
    {
        $v1 = [
            "appType" => 1,
            "guid" => "9980bd74-c4eb-4aac-9ae9-3fac8eeb58b5",
            "orderType" => "I",
            "orderNo" => "830000707458",
            "ebpCode" => "32016600B1",
            "ebpName" => "南京综保区跨境电子商务发展有限公司",
            "ebcCode" => "3201968B31",
            "ebcName" => "南京龙潭跨境贸易产业服务有限公司",
            "goodsValue" => 139.00,
            "freight" => 0.00,
            "discount" => 0.00,
            "taxTotal" => 0.00,
            "acturalPaid" => 139.00,
            "currency" => "142",
            "buyerRegNo" => "13951943776",
            "buyerName" => "郭祥飞",
            "buyerIdType" => "1",
            "buyerIdNumber" => "320382198410201932",
            "buyerTelephone" => "13951943776",
            "payCode" => "460116287K",
            "payName" => "新生支付有限公司",
            "payTransactionId" => "1022112061530033540",
            "batchNumbers" => "830000707458",
            "consignee" => "郭祥飞",
            "consigneeTelephone" => "13951943776",
            "consigneeAddress" => "江苏省-南京市-秦淮区1865创意园5a",
            "consigneeDitrict" => "210000",
            "note" => "备注"
        ];
        $v2 = [
            [
                "gnum" => 1,
                "itemNo" => "8809657112737",
                "itemName" => "绿豆面膜",
                "gmodel" => "5片",
                "itemDescribe" => "绿豆面膜",
                "barCode" => "8809657112737",
                "unit" => "140",
                "currency" => "142",
                "country" => "133",
                "qty" => 2,
                "price" => 69.50,
                "totalPrice" => 139.00,
                "netWeight" => 0.150,
                "note" => "备注"
            ]
        ];
        $v1['goodsListStr'] = $v2;
        var_dump($v1);
        $url = "http://222.190.144.83:19093/njeport/api/push311";//生产环境提交地址
        $serverCode = '000008';
        $info = $this->signMsg($v1, $url, $serverCode);

        $res = json_decode($info, true);

        var_dump($res);
    }

    /**
     *
     * @time 2021/11/03 14:02
     * 进口业务申报订单
     * @param Request $request
     * @return Json
     */
    public function declareOrder(Request $request): Response
    {
        $orderId = $request->post('orderId');
        if (!$orderId) {
            return CatchResponse::fail('缺少参数');
        }
        //订单表
        $where[] = ['orderId', 'in', $orderId];
        $where[] = ['status', '=', 0];
        $where[] = ['deleteStatus', '=', 0];
        $orderInfo = OrderModel::field('orderId,userId,amount,distributionfee,tax,realPayment,contactAddr,detailAddr,contactName,payOrderNo,buyerName,ConsigneeCode,contactMobile,ebpCode,ebpName,paycomCode,paycomName,discount,guid')->where($where)->select()->toArray();
        if (!$orderInfo) {
            return CatchResponse::fail('没有该订单');
        }
        // $guid = strtoupper(md5(time(),false)).rand(1000,9999);//唯一id  36位
//        $ebcCode = '3201968B31';//报文传输的企业代码（需要与接入客户端的企业身份一致）
//        $ebcName = '南京龙潭跨境贸易产业服务有限公司';//报文传输的企业名称（需要与接入客户端的企业身份一致）
        $ebcCode = '32016600B1';//报文传输的企业代码（需要与接入客户端的企业身份一致）
        $ebcName = '南京综保区跨境电子商务发展有限公司';//报文传输的企业名称（需要与接入客户端的企业身份一致）
        $orderArr = [];
        foreach ($orderInfo as $key => $value) {
            //主体信息
            $orderlist = [];
            if (empty($value['guid'])) {
                $orderlist['appType'] = 0;  //报送类型（0-新增 1-重新申报 2-变更申报。默认为0）;
                $orderlist['guid'] = '';
            } else {
                $orderlist['appType'] = 2;
                $orderlist['guid'] = $value['guid'];//(当appType=1或者2时，guid必填，值为新增申报成功返回的guid值。企业应该记录新增申报成功返回的guid。)
            }
            $ordersonInfo = OrderSonModel::field('orderId,RecordMaterialNo,barcode,num,spec_qty,price')
                ->where(['orderId'=>$value['orderId'],'deleteStatus'=>0])
                ->select()
                ->each(function (&$item){
                    $where['deleted_at'] = 0;
                    $where['barcode'] = $item['barcode'];
                    if(!empty($item['RecordMaterialNo'])){
                        $where['record_material_no'] = $item['RecordMaterialNo'];
                    }
                    $material_info = Db::name('db_customs_record_material')->field('net_weight,gross_weight,origin_country_code,trade_country_code,currency_code,g_code,g_model,g_name,currency_code,unit,unit1,unit2,qty1,qty2,record_material_no')->where($where)->find();
                    if ($material_info){
                        foreach ($material_info as $key => $value){
                            $item[$key] = $value;
                        }
                    }else{
                        $item = false;
                    }
                })
                ->toArray();

            if(!$ordersonInfo){
                return CatchResponse::fail($value['orderId'] . '订单，没有商品信息');
            }
            $isNull = array_search(null,$ordersonInfo);//看是否有null
            if($isNull !== false){
                return CatchResponse::fail($value['orderId'] . '订单，第'.($isNull+1).'项商品没有账册信息');
            }

            $orderlist['orderType'] = 'I';//订单类型(电子订单类型：I进口商品订单,E出口商品订单)
            $orderlist['orderNo'] = $value['orderId'];//订单编号
            $orderlist['ebpCode'] = $value['ebpCode'];//电商平台代码(电商平台的海关注册登记编号或统一社会信用代码。）
            $orderlist['ebpName'] = $value['ebpName'];//电商平台名称(电商平台的登记名称)
            $orderlist['ebcCode'] = $ebcCode;//电商企业代码（电商企业的海关注册登记编号。）
            $orderlist['ebcName'] = $ebcName;//电商企业名称（电商企业的海关注册登记名称。）
            $orderlist['goodsValue'] = $value['amount'];//商品价格(商品实际成交价，含非现金抵扣金额,精确到小数点后两位)
            $orderlist['freight'] = $value['distributionfee'];//运杂费(不包含在商品价格中的运杂费，无则填写"0",精确到小数点后两位)
            $orderlist['discount'] = $value['discount'];//代扣税款:非现金抵扣金额(使用积分、虚拟货币、代金券等非现金支付金额，无则填写"0",精确到小数点后两位)
            $orderlist['taxTotal'] = $value['tax'];//代扣税款(企业预先代扣的税款金额，无则填写“0”,精确到小数点后两位)
            $orderlist['acturalPaid'] = $value['realPayment'];//实际支付金额
            $orderlist['currency'] = 142;//币制（限定为人民币，填写“142”。）
            $orderlist['buyerRegNo'] = $value['contactMobile'];//订购人注册号(订购人的交易平台注册号。)
            $orderlist['buyerName'] = $value['buyerName'];//订购人姓名（订购人的真实姓名。）
            $orderlist['buyerIdType'] = 1;//订购人证件类型（1-身份证,2-其它。限定为身份证，填写“1”。）
            $orderlist['buyerIdNumber'] = $value['ConsigneeCode'];//订购人证件号码（订购人的身份证件号码。）
            $orderlist['buyerTelephone'] = $value['contactMobile'];//订购人电话
            $orderlist['payCode'] = $value['paycomCode'];//支付企业代码(支付企业的海关注册登记编号。)
            $orderlist['payName'] = $value['paycomName'];//支付企业名称(支付企业在海关注册登记的企业名称)
            $orderlist['payTransactionId'] = $value['payOrderNo'];//支付交易编号(支付企业唯一的支付流水号)
            $orderlist['batchNumbers'] = $value['orderId'];//商品批次号
            $orderlist['consignee'] = $value['contactName'];//收货人姓名(收货人姓名，必须与电子运单的收货人姓名一致。)
            $orderlist['consigneeTelephone'] = $value['contactMobile'];//收货人电话(收货人联系电话，必须与电子运单的收货人电话一致)
            $orderlist['consigneeAddress'] = $value['contactAddr'] . $value['detailAddr'];//收货地址(收货地址，必须与电子运单的收货地址一致)
            // $orderlist['consigneeDistrict'] = $orderInfo['contactAddr'];//收货地址行政区划代码(参照国家统计局公布的国家行政区划标准填制)
            $orderlist['note'] = '备注';//备注
            //子订单信息
            $orderSonArr = [];
            $gnum = 0;
            foreach ($ordersonInfo as $k => $v) {
                    $gnum++;
                    $v['num'] = (int)($v['num'] * $v['spec_qty']);
                    $v['price'] = round($v['price'] / $v['spec_qty'], 2);
                    $orderson = [];
                    $orderson['gnum'] = $gnum;//商品序号（从1开始的递增序号。）
                    $orderson['itemNo'] = $v['barcode'];//企业商品货号（电商企业自定义的商品货号（SKU））
                    $orderson['itemName'] = $v['g_name'];//企业商品品名称（交易平台销售商品的中文名称）替换斜杠避免签名错误
                    $orderson['gmodel'] = $v['g_model'];//商品规格型号  替换斜杠避免签名错误
                    $orderson['itemDescribe'] =  $v['g_name'];//企业商品描述（交易平台销售商品的描述信息） 替换斜杠避免签名错误

                    $orderson['barCode'] = $v['barcode'];//条形码（国际通用的商品条形码，一般由前缀部分、制造厂商代码、商品代码和校验码组成）
                    $orderson['unit'] = $v['unit'];//单位（海关标准的参数代码 《JGS-20海关业务代码集》- 计量单位代码）
                    // $orderson['currency'] = $v['currency_code'];//币制（限定为人民币，填写“142”。）
                    $orderson['currency'] = 142;//币制（限定为人民币，填写“142”。）
                    $orderson['country'] = $v['origin_country_code'];//原产国（地区）（海关标准的参数代码 《JGS-20海关业务代码集》 国家（地区）代码表填写代码。
                    $orderson['qty'] = $v['num'];//数量（按成交计量单位的实际数量，精确到小数点后两位）
                    $orderson['price'] = $v['price'];//单价（成交单价，精确到小数点后两位）
                    $orderson['totalPrice'] = round($v['num'] * $v['price'], 2);//总价（成交总价，精确到小数点后两位）
                    $orderson['netWeight'] = round($v['num'] * $v['net_weight'], 4);//净重
                    $orderson['note'] = '备注';//备注
                    $orderSonArr[] = $orderson;
            }
            $orderlist['goodsListStr'] = $orderSonArr;//子订单信息
            $orderArr[] = $orderlist;
        }
        //$url = "http://222.190.144.83:9093/njeport/api/push311";//测试环境提交地址
        $url = "http://222.190.144.83:19093/njeport/api/push311";//生产环境提交地址
        $serverCode = '000008';
        $successNum = 0;
        $successOrderNo = '';
        $failNum = 0;
        $failOrderNo = '';
        foreach ($orderArr as $k1 => $v1) {
            $info = $this->signMsg($v1, $url, $serverCode);
            $content = json_encode($v1, JSON_UNESCAPED_UNICODE) . "\r\n" . $info . "\r\n";
            $this->writeLog('order', $content);
            $res = json_decode($info, true);
            if ($res['success'] === true) {
                if ($v1['appType'] === 0) {
                    //新增存入guid
                    $res1 = $this->orderModel
                        ->where(array('orderId' => $v1['orderNo']))
                        ->update([
                            'push_order' => 1,
                            'guid' => $res['data'],
                            'returnInfo' => $res['msg']
                        ]);
                    if ($res1 > 0) {
                        $successNum += 1;
                        $successOrderNo .= $v1['orderNo'] . ',';
                    }
                } else {
                    $successNum += 1;
                    $successOrderNo .= $v1['orderNo'] . ',';
                }
            } else {
                $this->orderModel
                    ->where(array('orderId' => $v1['orderNo']))
                    ->update([
                        'returnInfo' => $res['msg']
                    ]);
                $failNum += 1;
                $failOrderNo .= $v1['orderNo'] . ',';
            }
        }
        if ($successNum > 0) {
            return CatchResponse::success([], '已推送成功' . $successNum . '项，失败' . $failNum . '项，稍等片刻可同步回执');
        } else {
            return CatchResponse::fail('推送失败');
        }
    }

    /**
     *
     * @time 2021/11/04 14:02
     * 查询订单回执
     * @param Request $request
     * @return Json
     */
    public function receiptOrder(Request $request)
    {
        //订单号
        $orderId = $request->param('orderId');

        //电商企业代码
        //$ebcCode = '3201968B31';//报文传输的企业代码（需要与接入客户端的企业身份一致）
        $ebcCode = '32016600B1';//报文传输的企业代码（需要与接入客户端的企业身份一致）
        if (!$orderId || !$ebcCode) {
            return CatchResponse::fail('缺少参数');
        }
        $orderIds = explode(',',$orderId);
        $success = 0;
        $fail = 0;
        $info = null;
        foreach ($orderIds as $key => $value){
            $data['orderNo'] = $value;
            $data['ebcCode'] = $ebcCode;
            //$url = "http://222.190.144.83:9093/njeport/api/query312";//测试环境
            $url = "http://222.190.144.83:19093/njeport/api/query312";//生产环境
            $serverCode = '000009';
            $info = $this->signMsg($data, $url, $serverCode);
            // $this->writeLog('orderReceipt',$info);
            $res = json_decode($info, true);
            if ($res['success'] === true) {
                if(count($res['data'])){
                    //回执按时间排序  取最新回执
                    $sort_column =  array_column($res['data'],'returnTime');
                    array_multisort($sort_column, SORT_DESC, $res['data']);
                    $datas['push_order'] = $res['data'][0]['returnStatus'];//回执状态
                    $datas['returnInfo'] = $res['data'][0]['returnInfo'];//回执信息
                    $where['orderId'] = $value;
                    Db::name('db_customs_order')->where($where)->save($datas);
                    $success++;
                }else{
                    $fail++;
                }
            } else {
                $fail++;
            }
        }
        return CatchResponse::success($info, '操作成功，'.$success.'条信息已同步，'.$fail.'条信息未同步');

    }

    /**
     *
     * @time 2021/11/04 14:02
     * 进口业务申报清单
     * @param Request $request
     * @return Json
     */
    public function declareDetailedList(Request $request): Response
    {
        $orderId = $request->post('orderId');
        if (!$orderId) {
            return CatchResponse::fail('缺少参数');
        }
        //订单表
        $where[] = ['orderId', 'in', $orderId];
        $where[] = ['status', '=', 0];
        $where[] = ['deleteStatus', '=', 0];
        $orderInfo = OrderModel::field('orderId,userId,amount,distributionfee,tax,waybill_status,realPayment,contactAddr,detailAddr,contactName,payOrderNo,buyerName,ConsigneeCode,contactMobile,snum,NetWeight,ebpCode,ebpName,paycomCode,paycomName,task_no,flight_no,rough_weight,NetWeight,express_no,clear_guid,invt_no,bill_no,push_order,push_inventory,copNo')->where($where)->select()->toArray();
        if (!$orderInfo) {
            return CatchResponse::fail('没有该订单');
        }

        $pushDate = date('Ymd');
        $logisticsCode = '3201989058';//物流企业代码
        $logisticsName = '中国外运长江有限公司';//物流企业名称
        // $logisticsCode = '4403180939';//物流企业代码
        // $logisticsName = '顺丰速运有限公司';//物流企业名称
        //$ebcCode = '3201968B31';//电商企业代码
        //$ebcName = '南京龙潭跨境贸易产业服务有限公司';//电商企业名称
        $ebcCode = '32016600B1';//电商企业代码
        $ebcName = '南京综保区跨境电子商务发展有限公司';//电商企业名称

        $orderArr = [];

        foreach ($orderInfo as $key => $value) {
            //主体信息
            $orderlist = [];

//            $ordersonInfo = OrderSonModel::field('a.orderId,a.barcode,a.num,a.spec_qty,a.price,b.net_weight,b.gross_weight,b.origin_country_code,b.trade_country_code,b.currency_code,b.g_code,b.g_model,b.g_name,b.currency_code,b.unit,b.unit1,b.unit2,b.qty1,b.qty2,b.record_material_no')
//                ->alias('a')
//                ->leftJoin('db_customs_record_material b','a.barcode = b.barcode')
//                ->where(['a.orderId'=>$value['orderId'],'a.deleteStatus'=>0,'b.deleted_at'=>0])
//                ->select()
//                ->toArray();
            $ordersonInfo = OrderSonModel::field('orderId,RecordMaterialNo,barcode,num,spec_qty,price')
                ->where(['orderId'=>$value['orderId'],'deleteStatus'=>0])
                ->select()
                ->each(function (&$item){
                    $where['deleted_at'] = 0;
                    $where['barcode'] = $item['barcode'];
                    if(!empty($item['RecordMaterialNo'])){
                        $where['record_material_no'] = $item['RecordMaterialNo'];
                    }
                    $material_info = Db::name('db_customs_record_material')->field('net_weight,gross_weight,origin_country_code,trade_country_code,currency_code,g_code,g_model,g_name,currency_code,unit,unit1,unit2,qty1,qty2,record_material_no')->where($where)->find();
                    if ($material_info){
                        foreach ($material_info as $key => $value){
                            $item[$key] = $value;
                        }
                    }else{
                        $item = false;
                    }
                })
                ->toArray();

            if(!$ordersonInfo){
                return CatchResponse::fail($value['orderId'] . '订单，没有商品信息');
            }
            $isNull = array_search(null,$ordersonInfo);//看是否有null
            if($isNull !== false){
                return CatchResponse::fail($value['orderId'] . '订单，第'.($isNull+1).'项商品没有账册信息');
            }

            if (empty($value['clear_guid'])) {
                $orderlist['appType'] = 0;  //报送类型（0： 新增申报；1:重新申报；2：变更申报）;
                $orderlist['guid'] = '';
                $orderlist['invtNo'] = '';//清单编号
            } else {
                $orderlist['appType'] =  1 ;  //报送类型（0： 新增申报；1:重新申报；2：变更申报）;
                $orderlist['guid'] = $value['clear_guid'];//(当appType=1或者2时，guid必填，值为新增申报成功返回的guid值。企业应该记录新增申报成功返回的guid。)
                $orderlist['invtNo'] =  '' ;  //报送类型（0： 新增申报；1:重新申报；2：变更申报）;
            }
            $orderlist['customsCode'] = 2378;//申报地海关代码
            $orderlist['orderNo'] = $value['orderId'];//订单编号
            $orderlist['ebpCode'] = $value['ebpCode'];//电商平台代码(电商平台的海关注册登记编号或统一社会信用代码。）
            $orderlist['ebpName'] = $value['ebpName'];//电商平台名称(电商平台的登记名称)
            $orderlist['ebcCode'] = $ebcCode;//电商企业代码（电商企业的海关注册登记编号。）
            $orderlist['ebcName'] = $ebcName;//电商企业名称（电商企业的海关注册登记名称。）

            if ($value['push_inventory'] === 800) {
                return CatchResponse::fail($value['orderId'] . '订单，已放行状态不可以重新申报');
            }
            if ($value['push_order'] === 0) {
                return CatchResponse::fail($value['orderId'] . '订单，请先推送订单');
            }
            if ($value['waybill_status']!==2&&$value['waybill_status']!==120) {
                return CatchResponse::fail($value['orderId'] . '订单，请先推送运单');
            }

            $orderlist['logisticsNo'] = $value['bill_no'];//物流运单/快递单号（对接物流企业）
            $orderlist['logisticsCode'] = $logisticsCode;//物流企业代码（物流企业的海关注册登记编号。）
            $orderlist['logisticsName'] = $logisticsName;//物流企业名称（物流企业的海关注册登记名称。）
            $orderlist['copNo'] = $value['copNo'];//企业内部标识单证的编号。 必填
            $orderlist['preNo'] = '';//电子口岸标识单证的编号。
            // $orderlist['assureCode'] = $value['ebpCode'];//担保企业
            $orderlist['assureCode'] = $ebcCode;//担保企业
            $orderlist['emsNo'] = 'T2378W000036';// 账册编号

            $orderlist['ieFlag'] = 'I';//订单类型(电子订单类型：I进口)
            $orderlist['declTime'] = $pushDate;//申报日期
            $orderlist['portCode'] = 2378;//口岸海关代码
            $orderlist['ieDate'] = $pushDate;//进口日期 可免填
            $orderlist['buyerIdType'] = 1;//订购人证件类型
            $orderlist['buyerIdNumber'] = $value['ConsigneeCode'];//订购人证件号码
            $orderlist['buyerName'] = $value['buyerName'];//订购人姓名
            $orderlist['buyerTelephone'] = $value['contactMobile'];//订购人电话
            $orderlist['consigneeAddress'] = $value['contactAddr'] . $value['detailAddr'];//收件地址
            $orderlist['agentCode'] = $value['ebpCode'];//申报企业代码
            $orderlist['agentName'] = $value['ebpName'];//申报企业名称
            $orderlist['areaCode'] = $ebcCode;//区内企业代码
            $orderlist['areaName'] = $ebcName;//区内企业名称
            $orderlist['tradeMode'] = 1210;//贸易方式
            $orderlist['trafMode'] = 7;//运输方式 。直购进口指跨境段物流运输方式，保税进口指二线出区物流运输方式
            // $orderlist['trafNo'] = '';//运输工具编号 直购进口必填 保税进口免填
            // $orderlist['voyageNo'] = $value['flight_no'];//航班航次号 直购进口必填 保税进口免填
            // $orderlist['billNo'] = $value['get_bill_no'];//提运单号 直购进口必填 保税进口免填
            // $orderlist['loctNo'] = 2378;//监管场所代码 非必填
            $orderlist['country'] = 142;//起运国（地区）
            $orderlist['freight'] = $value['distributionfee'];//运费
            $orderlist['insuredFee'] = '0';//保费 物流企业实际收取的商品保价费用
            $orderlist['currency'] = 142;//币制
            $orderlist['packNo'] = 1;//件数
            $orderlist['note'] = '';//备注

            $orderlistArr = array();
            $netWeight = 0;
            $rough_weight = 0;
            $gnum = 0;
            foreach ($ordersonInfo as $k => $v) {
                $gnum++;
                //组合商品  包含商品编码和数量
                $v['num'] = (int)($v['num'] * $v['spec_qty']);
                $v['price'] = round($v['price'] / $v['spec_qty'], 2);
                $orderson = array();
                $orderson['gnum'] = $gnum;//商品序号（从1开始的递增序号。）
                $orderson['itemRecordNo'] = $v['record_material_no'];//账册备案料号
                $orderson['itemNo'] = $v['barcode'];//企业商品货号（电商企业自定义的商品货号（SKU））

                $orderson['gcode'] = $v['g_code'];//海关编码
                $orderson['itemName'] = $v['g_name'];//企业商品品名称（交易平台销售商品的中文名称）
                $orderson['gname'] = $v['g_name'];//企业商品品名称（交易平台销售商品的中文名称）
                $orderson['gmodel'] = $v['g_model'];//商品规格型号
                $orderson['barCode'] = $v['barcode'];//条形码
                $orderson['country'] = $v['origin_country_code'];//原产国（地区）
                //$orderson['tradeCountry'] = 142;//贸易国
                // $orderson['currency'] = $v['currency_code'];//币制（限定为人民币，填写“142”。）
                $orderson['currency'] = 142;//币制（限定为人民币，填写“142”。）
                $orderson['qty'] = $v['num'];//数量（按成交计量单位的实际数量，精确到小数点后两位）
                $orderson['qty1'] = round($v['qty1'] * $v['num'],5);//法定数量
                $orderson['unit'] = $v['unit'];//计量单位
                $orderson['unit1'] = $v['unit1'];//法定计量单位

                $netWeight += $v['net_weight'] * $v['num'];
                $rough_weight += $v['gross_weight'] * $v['num'];
                if (!empty($v['unit2'])) {
                    $orderson['qty2'] = round($v['qty2'] * $v['num'],5);//法定第二数量
                    $orderson['unit2'] = $v['unit2'];//法定第二计量单位
                }
                $orderson['price'] = $v['price'];//单价
                $orderson['totalPrice'] = round($v['num'] * $v['price'],2);//总价
                $orderson['note'] = '';//备注
                $orderlistArr[] = $orderson;

            }
            $orderlist['netWeight'] = round($netWeight,5);//总净重（公斤）
            $orderlist['grossWeight'] = round($rough_weight,5);//总毛重（公斤）
            $orderlist['goodsListStr'] = $orderlistArr;//子订单信息
            $orderArr[] = $orderlist;
        }
        // $url = "http://222.190.144.83:9093/njeport/api/push621";//测试环境提交地址
        $url = "http://222.190.144.83:19093/njeport/api/push621";//生产环境提交地址
        $serverCode = '000010';
        $successNum = 0;
        $successOrderNo = '';
        $failNum = 0;
        $failOrderNo = '';
        foreach ($orderArr as $k1 => $v1) {
            $info = $this->signMsg($v1, $url, $serverCode);
            $content = json_encode($v1, JSON_UNESCAPED_UNICODE) . "\r\n" . $info . "\r\n";
            $this->writeLog('detailedList', $content);
            $res = json_decode($info, true);
            if ($res['success'] === true) {
                if ($v1['appType'] === 0) {
                    //新增存入guid
                    $res1 = $this->orderModel
                        ->where(array('orderId' => $v1['orderNo']))
                        ->update([
                            'push_inventory' => 1,
                            'clear_guid' => $res['data'],
                            'clear_returnInfo' => $res['msg']
                        ]);
                    if ($res1 > 0) {
                        $successNum += 1;
                        $successOrderNo .= $v1['orderNo'] . ',';
                    }
                } else {
                    $successNum += 1;
                    $successOrderNo .= $v1['orderNo'] . ',';
                }
            } else {
                $this->orderModel
                    ->where(array('orderId' => $v1['orderNo']))
                    ->update([
                        'clear_returnInfo' => $res['msg']
                    ]);
                $failNum += 1;
                $failOrderNo .= $v1['orderNo'] . ',';
            }
        }
        if ($successNum > 0) {
            return CatchResponse::success([], '清单已推送成功' . $successNum . '项，失败' . $failNum . '项，稍等片刻可同步回执');
        } else {
            return CatchResponse::fail('清单推送失败');
        }
    }

    /**
     *
     * @time 2021/11/04 14:02
     * 查询清单回执
     * @param Request $request
     * @return Json
     */
    public function receiptDetailedList(Request $request)
    {
        //订单号/企业唯一编码
        $orderIds = $request->param();
        unset($orderIds['creator_id']);
        if (empty($orderIds)) {
            return CatchResponse::fail('缺少参数');
        }
        // $orderIds = explode(',',$infos);
        $success = 0;
        $fail = 0;
        $info = null;
        foreach ($orderIds as $key => $value){
            $data['copNo'] = $value['copNo'];
            //$url = "http://222.190.144.83:9093/njeport/api/query622";//测试环境
            $url = "http://222.190.144.83:19093/njeport/api/query622";//生产环境
            $serverCode = '000014';
            $info = $this->signMsg($data, $url, $serverCode);

            //$this->writeLog('detailedReceipt',$copNo.$info);
            $res = json_decode($info, true);
//            return CatchResponse::success($res, $res);
            if ($res['success'] === true) {
                if(count($res['data'])){
                    $last = count($res['data'])-1;
                    //回执状态
                    $datas['push_inventory'] = $res['data'][$last]['returnStatus'];
                    $datas['clear_returnInfo'] = $res['data'][$last]['returnInfo'];

                    if(!empty($res['data'][$last]['invtNo'])){
                        $datas['invt_no'] = $res['data'][$last]['invtNo'];
                    }else{
                        $datas['invt_no'] = '';
                    }

                    if($res['data'][$last]['returnStatus'] === '800'){
                        $datas['completeDateTime'] = (int)($res['data'][$last]['returnTime']/1000);
                    }

                    //错误码-621041 是已放行,重复申报状态 或者退单重复申报状态
                    if($res['data'][$last]['returnStatus'] === '-621041'&&strpos($res['data'][$last]['returnInfo'],'800-实货放行') !== false){
                        $datas['push_inventory'] = '800';
                        $datas['clear_returnInfo'] = '[Code:2600;Desc:已放行]';
                    }

                    $where['orderId'] = $value['orderId'];
                    $where['copNo'] = $value['copNo'];
                    Db::name('db_customs_order')->where($where)->save($datas);
                    $success++;
                }else{
                    $fail++;
                }
            } else {
                $fail++;
            }
        }
        return CatchResponse::success($info, '操作成功，'.$success.'条信息已同步，'.$fail.'条信息未同步');

    }

    //导出海关订单xml
    public function exportOrderXml(Request $request)
    {
        $orderId = $request->post('orderId');
        if (!$orderId) {
            return CatchResponse::fail('缺少参数');
        }
        //订单表
        $where[] = ['orderId', 'in', $orderId];
        $where[] = ['status', '=', 0];
        $where[] = ['deleteStatus', '=', 0];
        $orderInfo = OrderModel::field('orderId,userId,amount,distributionfee,tax,realPayment,contactAddr,detailAddr,contactName,payOrderNo,ConsigneeCode,contactMobile,snum,NetWeight,ebpCode,ebpName,ebcCode,ebcName,paycomCode,paycomName,task_no,discount')->where($where)->select()->toArray();

        //订单子表
        $where1[] = ['orderId', 'in', $orderId];
        $where1[] = ['deleteStatus', '=', 0];
        $ordersonInfo = OrderSonModel::field('orderId,productId,productName,barcode,num,weight,price,business_addr,GModel,Unit,spec_qty')->where($where1)->select()->toArray();

        if (!$orderInfo) {
            return CatchResponse::fail('没有该订单');
        }

        if (!$ordersonInfo) {
            return CatchResponse::fail('该订单,没有商品信息');
        }
        $appTime = date('YmdHis');
        //$ebcCode = '3201968B31';//电商企业代码
        //$ebcName = '南京龙潭跨境贸易产业服务有限公司';//电商企业名称
        $ebcCode = '32016600B1';//电商企业代码
        $ebcName = '南京综保区跨境电子商务发展有限公司';//电商企业名称
        $guid = strtoupper(md5(time(), false)) . rand(1000, 9999);//唯一id  36位
        //查询订单信息
        foreach ($orderInfo as $key => $value) {
            //主单数据

            $orderlist = [];
            $orderlist['guid'] = $guid;//唯一id机器码
            $orderlist['appType'] = 1;//报送类型（1-新增 2-变更 3-删除。默认为1）;
            $orderlist['appTime'] = $appTime;//报送时间（格式:YYYYMMDDhhmmss）\n
            $orderlist['appStatus'] = 2;//业务状态（业务状态:1-暂存,2-申报,默认为1。）
            $orderlist['orderType'] = 'I';//订单类型(电子订单类型：I进口)
            $orderlist['orderNo'] = $value['orderId'];//订单编号
            $orderlist['ebpCode'] = $value['ebpCode'];//电商平台代码(电商平台的海关注册登记编号或统一社会信用代码。）
            $orderlist['ebpName'] = $value['ebpName'];//电商平台名称(电商平台的登记名称)
            $orderlist['ebcCode'] = $ebcCode;//电商企业代码（电商企业的海关注册登记编号。）
            $orderlist['ebcName'] = $ebcName;//电商企业名称（电商企业的海关注册登记名称。）
            $orderlist['goodsValue'] = $value['amount'];//商品价格(商品实际成交价，含非现金抵扣金额,精确到小数点后两位)
            $orderlist['freight'] = $value['distributionfee'];//运杂费(不包含在商品价格中的运杂费，无则填写"0",精确到小数点后两位)
            $orderlist['discount'] = $value['discount'];//非现金抵扣金额(使用积分、虚拟货币、代金券等非现金支付金额，无则填写"0",精确到小数点后两位)
            $orderlist['taxTotal'] = $value['tax'];//代扣税款(企业预先代扣的税款金额，无则填写“0”,精确到小数点后两位)
            $orderlist['acturalPaid'] = $value['realPayment'];//实际支付
            $orderlist['currency'] = 142;//币制（限定为人民币，填写“142”。）
            $orderlist['buyerRegNo'] = $value['contactMobile'];//订购人注册号(订购人的交易平台注册号。)
            $orderlist['buyerName'] = $value['contactName'];//订购人姓名（订购人的真实姓名。）
            $orderlist['buyerTelephone'] = $value['contactMobile'];//订购人电话
            $orderlist['buyerIdType'] = 1;//订购人证件类型（1-身份证,2-其它。限定为身份证，填写“1”。）
            $orderlist['buyerIdNumber'] = $value['ConsigneeCode'];//订购人证件号码（订购人的身份证件号码。）

            $orderlist['payCode'] = $value['paycomCode'];//支付企业代码(支付企业的海关注册登记编号。)
            $orderlist['payName'] = $value['paycomName'];//支付企业名称(支付企业在海关注册登记的企业名称)
            $orderlist['payTransactionId'] = $value['payOrderNo'];//支付交易编号(支付企业唯一的支付流水号)
            $orderlist['batchNumbers'] = $value['orderId'];//商品批次号
            $orderlist['consignee'] = $value['contactName'];//收货人姓名(收货人姓名，必须与电子运单的收货人姓名一致。)
            $orderlist['consigneeTelephone'] = $value['contactMobile'];//收货人电话(收货人联系电话，必须与电子运单的收货人电话一致)
            $orderlist['consigneeAddress'] = $value['contactAddr'] . $value['detailAddr'];//收货地址(收货地址，必须与电子运单的收货地址一致)
            //$orderlist['consigneeDistrict'] = '';//收货地址行政区划代码(参照国家统计局公布的国家行政区划标准填制)
            $orderlist['note'] = '备注';//备注

            $orderlistArr = [];
            $gnum = 0;
            foreach ($ordersonInfo as $k => $v) {
                if ($v['orderId'] === $value['orderId']) {
                    $gnum++;
                    //组合商品
                    $v['num'] = (int)($v['num'] * $v['spec_qty']);
                    $v['price'] = round($v['price'] / $v['spec_qty'], 2);
                    $orderson = [];

                    $orderson['gnum'] = $gnum;//商品序号（从1开始的递增序号。）
                    $orderson['itemNo'] = $v['barcode'];//企业商品货号（电商企业自定义的商品货号（SKU））
                    $orderson['itemName'] = $v['productName'];//企业商品品名称（交易平台销售商品的中文名称）
                    $orderson['gmodel'] = $v['GModel'];//商品规格型号
                    $orderson['itemDescribe'] = $v['productName'];//企业商品描述（交易平台销售商品的描述信息）
                    $orderson['barCode'] = $v['barcode'];//条形码（国际通用的商品条形码，一般由前缀部分、制造厂商代码、商品代码和校验码组成）
                    $orderson['unit'] = $v['Unit'];//单位（海关标准的参数代码 《JGS-20海关业务代码集》- 计量单位代码）
                    $orderson['qty'] = $v['num'];//数量（按成交计量单位的实际数量，精确到小数点后两位）
                    $orderson['price'] = $v['price'];//单价（成交单价，精确到小数点后两位）
                    $orderson['totalPrice'] = $v['num'] * $v['price'];//总价（成交总价，精确到小数点后两位）
                    $orderson['currency'] = 142;//币制（限定为人民币，填写“142”。）
                    $orderson['country'] = $v['business_addr'];//原产国（地区）（海关标准的参数代码 《JGS-20海关业务代码集》 国家（地区）代码表填写代码。
                    $orderson['note'] = '备注';//备注
                    $orderlistArr[] = $orderson;
                }
            }
            $orderlist['orderlist'] = $orderlistArr;//子订单信息
            $orderArr[] = $orderlist;
        }


        $xml = $this->createOrderXml($orderArr, $guid);
        return CatchResponse::success($xml);

    }

    //导出海关清单xml
    public function exportInventoryXml(Request $request)
    {
        $orderId = $request->post('orderId');
        if (!$orderId) {
            return CatchResponse::fail('缺少参数');
        }
        //订单表
        $where[] = ['orderId', 'in', $orderId];
        $where[] = ['status', '=', 0];
        $where[] = ['deleteStatus', '=', 0];
        $orderInfo = OrderModel::field('orderId,userId,amount,distributionfee,tax,realPayment,contactAddr,detailAddr,contactName,payOrderNo,buyerName,ConsigneeCode,contactMobile,snum,NetWeight,ebpCode,ebpName,paycomCode,paycomName,task_no,flight_no,rough_weight,NetWeight,express_no,clear_guid,bill_no')->where($where)->select()->toArray();

        //订单子表
        $where1[] = ['orderId', 'in', $orderId];
        $where1[] = ['deleteStatus', '=', 0];
        $ordersonInfo = OrderSonModel::field('orderId,productId,productName,barcode,num,weight,price,GCode,GModel,Unit,Unit1,Unit2,Qty,Qty1,Qty2,business_addr,RecordMaterialNo,weight,rough_weight,spec_qty')->where($where1)->select()->toArray();

        if (!$orderInfo) {
            return CatchResponse::fail('没有该订单');
        }

        if (!$ordersonInfo) {
            return CatchResponse::fail('该订单,没有商品信息');
        }
        $appTime = date('YmdHis');
        $pushDate = date('Ymd');
        //$ebcCode = '3201968B31';//电商企业代码
        //$ebcName = '南京龙潭跨境贸易产业服务有限公司';//电商企业名称
        $ebcCode = '32016600B1';//电商企业代码
        $ebcName = '南京综保区跨境电子商务发展有限公司';//电商企业名称
//        $logisticsCode = '3201981249';//物流企业代码
//        $logisticsName = '江苏时进国际物流有限公司';//物流企业名称
        $logisticsCode = '3201989058';//物流企业代码
        $logisticsName = '中国外运长江有限公司';//物流企业名称
        $guid = strtoupper(md5(time(), false)) . rand(1000, 9999);//唯一id  36位
        //查询订单信息
        foreach ($orderInfo as $key => $value) {

            $orderlist = [];
            $orderKey = $key + 1;//关联单号
            $orderlist['guid'] = $guid;//唯一id机器码
            $orderlist['appType'] = 1;//报送类型（1-新增 2-变更 3-删除。默认为1）;
            $orderlist['appTime'] = $appTime;//报送时间（格式:YYYYMMDDhhmmss）\n
            $orderlist['appStatus'] = 2;//业务状态（业务状态:1-暂存,2-申报,默认为1。）
            $orderlist['orderNo'] = $value['orderId'];//订单编号
            $orderlist['ebpCode'] = $value['ebpCode'];//电商平台代码(电商平台的海关注册登记编号或统一社会信用代码。）
            $orderlist['ebpName'] = $value['ebpName'];//电商平台名称(电商平台的登记名称)
            $orderlist['ebcCode'] = $ebcCode;//电商企业代码（电商企业的海关注册登记编号。）
            $orderlist['ebcName'] = $ebcName;//电商企业名称（电商企业的海关注册登记名称。）
            $orderlist['logisticsNo'] = $value['bill_no'];//物流运单编号
            $orderlist['logisticsCode'] = $logisticsCode;//物流企业代码（物流企业的海关注册登记编号。）
            $orderlist['logisticsName'] = $logisticsName;//物流企业名称（物流企业的海关注册登记名称。）
            $orderlist['copNo'] = $value['orderId'];//企业内部标识单证的编号。 必填
            $orderlist['preNo'] = '';//电子口岸标识单证的编号。
            $orderlist['assureCode'] = $ebcCode;//担保企业
            $orderlist['emsNo'] = 'T2378W000027';//账册编号
            $orderlist['invtNo'] = '';//账册编号
            $orderlist['ieFlag'] = 'I';//订单类型(电子订单类型：I进口)
            $orderlist['declTime'] = $pushDate;//申报日期
            $orderlist['customsCode'] = 2378;//申报海关代码
            $orderlist['portCode'] = 2378;//口岸海关代码
            $orderlist['ieDate'] = $pushDate;//进口日期 可免填
            $orderlist['buyerIdType'] = 1;//订购人证件类型
            $orderlist['buyerIdNumber'] = $value['ConsigneeCode'];//订购人证件号码
            $orderlist['buyerName'] = $value['contactName'];//订购人姓名
            $orderlist['buyerTelephone'] = $value['contactMobile'];//订购人电话
            $orderlist['consigneeAddress'] = $value['contactAddr'] . $value['detailAddr'];//收件地址
            $orderlist['agentCode'] = $value['ebpCode'];//申报企业代码
            $orderlist['agentName'] = $value['ebpName'];//申报企业名称
//            $orderlist['areaCode'] = '3201665004';//区内企业代码
//            $orderlist['areaName'] = '南京万通国际仓储物流有限公司';//区内企业名称
            $orderlist['areaCode'] = $logisticsCode;//区内企业代码
            $orderlist['areaName'] = $logisticsName;//区内企业名称
            $orderlist['tradeMode'] = 1210;//贸易方式
            $orderlist['trafMode'] = 7;//运输方式 。直购进口指跨境段物流运输方式，保税进口指二线出区物流运输方式
            //$orderlist['trafNo'] = '';//运输工具编号 直购进口必填 保税进口免填
            //$orderlist['voyageNo'] = $orderInfo['flight_no'];//航班航次号 直购进口必填 保税进口免填
            //$orderlist['billNo'] = $orderInfo['get_bill_no'];//提运单号 直购进口必填 保税进口免填
            //$orderlist['loctNo'] = 2378;//监管场所代码 非必填
            //$orderlist['licenseNo'] = '';//许可证件号 非必填
            $orderlist['country'] = 142;//起运国（地区）
            $orderlist['freight'] = '0';//运费
            $orderlist['insuredFee'] = '0';//保费 物流企业实际收取的商品保价费用
            $orderlist['currency'] = 142;//币制
            //$orderlist['wrapType'] = '';//包装种类代码件数 非必填
            $orderlist['packNo'] = 1;//件数


            $orderlistArr = [];
            $netWeight = 0;
            $rough_weight = 0;
            $gnum = 0;
            foreach ($ordersonInfo as $k => $v) {
                if ($v['orderId'] === $value['orderId']) {
                    $gnum++;
                    //组合商品
                    $v['num'] = (int)($v['num'] * $v['spec_qty']);
                    $v['price'] = round($v['price'] / $v['spec_qty'], 2);
                    $orderson = array();
                    $orderson['gnum'] = $gnum;//商品序号（从1开始的递增序号。）
                    $orderson['itemRecordNo'] = $v['RecordMaterialNo'];//账册备案料号
                    $orderson['itemNo'] = $v['barcode'];//企业商品货号（电商企业自定义的商品货号（SKU））
                    $orderson['itemName'] = $v['productName'];//企业商品品名称（交易平台销售商品的中文名称）
                    $orderson['gcode'] = $v['GCode'];//海关编码
                    $orderson['gname'] = $v['productName'];//企业商品品名称（交易平台销售商品的中文名称）
                    $orderson['gmodel'] = $v['GModel'];//商品规格型号
                    $orderson['barCode'] = $v['barcode'];//条形码
                    $orderson['country'] = $v['business_addr'];//原产国（地区）
                    //$orderson['tradeCountry'] = 142;//贸易国
                    $orderson['currency'] = 142;//币制（限定为人民币，填写“142”。）
                    $orderson['qty'] = $v['num'];//数量（按成交计量单位的实际数量，精确到小数点后两位）
                    $orderson['unit'] = $v['Unit'];//计量单位
                    $orderson['qty1'] = $v['Qty1'] * $v['num'];//法定数量
                    $orderson['unit1'] = $v['Unit1'];//法定计量单位
                    $netWeight += $v['weight'] * $v['num'];
                    $rough_weight += $v['rough_weight'] * $v['num'];
                    if (!empty($v['Unit2'])) {
                        $orderson['qty2'] = $v['Qty2'] * $v['num'];//法定第二数量
                        $orderson['unit2'] = $v['Unit2'];//法定第二计量单位
                    }

                    $orderson['price'] = $v['price'];//单价
                    $orderson['totalPrice'] = $v['num'] * $v['price'];//总价
                    $orderson['note'] = '';//备注
                    $orderlistArr[] = $orderson;
                }
            }
            $orderlist['netWeight'] = round($netWeight, 4);//净重（公斤）
            $orderlist['grossWeight'] = round($rough_weight, 4);//毛重（公斤）
            $orderlist['orderlist'] = $orderlistArr;//子订单信息
            $orderArr[] = $orderlist;

        }
        $xml = $this->createInventoryXml($orderArr, $guid);
        return CatchResponse::success($xml);

    }

    //海关清单xml文件
    public function createOrderXml($order, $guid)
    {
//        $copCode = '3201968B31';//报文传输的企业代码（需要与接入客户端的企业身份一致）
//        $copName = '南京龙潭跨境贸易产业服务有限公司';//报文传输的企业名称（需要与接入客户端的企业身份一致）
//        $dxpMode = 'DXP';//默认为DXP；指中国电子口岸数据交换平台
//        $dxpId = 'DXPENT0000012866';//向中国电子口岸数据中心申请数据交换平台的用户编号
        $copCode = '32016600B1';//报文传输的企业代码（需要与接入客户端的企业身份一致）
        $copName = '南京综保区跨境电子商务发展有限公司';//报文传输的企业名称（需要与接入客户端的企业身份一致）
        $dxpMode = 'DXP';//默认为DXP；指中国电子口岸数据交换平台
        $dxpId = 'DXPENT0000468021';//向中国电子口岸数据中心申请数据交换平台的用户编号


        $xml = new \DOMDocument('1.0', 'utf-8');//建立DOM对象
        $xml->formatOutput = true;
        $ceb = $xml->createElement('ceb:CEB311Message');
        $ceb = $xml->appendChild($ceb);
        $name1 = $xml->createAttribute('guid');
        $name1->value = $guid;
        $ceb->appendChild($name1);

        $name2 = $xml->createAttribute('version');
        $name2->value = '1.0';
        $ceb->appendChild($name2);

        $name3 = $xml->createAttribute('xmlns:ceb');
        $name3->value = 'http://www.chinaport.gov.cn/ceb';
        $ceb->appendChild($name3);

        $name4 = $xml->createAttribute('xmlns:xsi');
        $name4->value = 'http://www.w3.org/2001/XMLSchema-instance';
        $ceb->appendChild($name4);

        foreach ($order as $key => $value) {
            //创建主单节点
            $Order = $ceb->appendChild($xml->createElement('ceb:Order'));
            $OrderHead = $Order->appendChild($xml->createElement('ceb:OrderHead'));

            $orderlist = $value['orderlist'];
            unset($value['orderlist']);
            //主单参数 除子订单之外的参数
            foreach ($value as $k => $vo) {
                //主单参数节点
                $order_obj = $OrderHead->appendChild($xml->createElement('ceb:' . $k));
                if ($vo != "") {
                    $order_obj->appendChild($xml->createTextNode($vo));
                }
            }

            //创建子单节点
            foreach ($orderlist as $k => $vo) {
                $OrderList = $Order->appendChild($xml->createElement('ceb:OrderList'));

                foreach ($vo as $p => $q) {
                    //子单参数节点
                    $list_obj = $OrderList->appendChild($xml->createElement('ceb:' . $p));
                    if ($q != "") {
                        $list_obj->appendChild($xml->createTextNode($q));
                    }
                }
            }
        }

        //基础报文传输实体节点
        $BaseTransfer = $ceb->appendChild($xml->createElement('ceb:BaseTransfer'));

        //报文传输的企业代码
        $Base_obj1 = $BaseTransfer->appendChild($xml->createElement('ceb:copCode'));
        $Base_obj1->appendChild($xml->createTextNode($copCode));
        //报文传输的企业名称
        $Base_obj2 = $BaseTransfer->appendChild($xml->createElement('ceb:copName'));
        $Base_obj2->appendChild($xml->createTextNode($copName));
        //默认为DXP；指中国电子口岸数据交换平台
        $Base_obj3 = $BaseTransfer->appendChild($xml->createElement('ceb:dxpMode'));
        $Base_obj3->appendChild($xml->createTextNode($dxpMode));
        //向中国电子口岸数据中心申请数据交换平台的用户编号
        $Base_obj4 = $BaseTransfer->appendChild($xml->createElement('ceb:dxpId'));
        if ($dxpId != "") {
            $Base_obj4->appendChild($xml->createTextNode($dxpId));
        }

        header('Content-type:text/xml;charset=utf-8');
        header('Content-Disposition: attachment; filename="CEB311Message.xml"');
        return $xml->saveXML();
    }

    //海关清单xml文件
    public function createInventoryXml($order, $guid)
    {
//        $copCode = '3201968B31';//报文传输的企业代码（需要与接入客户端的企业身份一致）
//        $copName = '南京龙潭跨境贸易产业服务有限公司';//报文传输的企业名称（需要与接入客户端的企业身份一致）
//        $dxpMode = 'DXP';//默认为DXP；指中国电子口岸数据交换平台
//        $dxpId = 'DXPENT0000012866';//向中国电子口岸数据中心申请数据交换平台的用户编号
        $copCode = '32016600B1';//报文传输的企业代码（需要与接入客户端的企业身份一致）
        $copName = '南京综保区跨境电子商务发展有限公司';//报文传输的企业名称（需要与接入客户端的企业身份一致）
        $dxpMode = 'DXP';//默认为DXP；指中国电子口岸数据交换平台
        $dxpId = 'DXPENT0000468021';//向中国电子口岸数据中心申请数据交换平台的用户编号
        $xml = new \DOMDocument('1.0', 'utf-8');//建立DOM对象
        $xml->formatOutput = true;
        $ceb = $xml->createElement('ceb:CEB621Message');
        $ceb = $xml->appendChild($ceb);
        $name1 = $xml->createAttribute('guid');
        $name1->value = $guid;
        $ceb->appendChild($name1);

        $name2 = $xml->createAttribute('version');
        $name2->value = '1.0';
        $ceb->appendChild($name2);

        $name3 = $xml->createAttribute('xmlns:ceb');
        $name3->value = 'http://www.chinaport.gov.cn/ceb';
        $ceb->appendChild($name3);

        $name4 = $xml->createAttribute('xmlns:xsi');
        $name4->value = 'http://www.w3.org/2001/XMLSchema-instance';
        $ceb->appendChild($name4);

        foreach ($order as $key => $value) {
            //创建主单节点
            $Order = $ceb->appendChild($xml->createElement('ceb:Inventory'));
            $OrderHead = $Order->appendChild($xml->createElement('ceb:InventoryHead'));

            $orderlist = $value['orderlist'];
            unset($value['orderlist']);
            //主单参数 除子订单之外的参数
            foreach ($value as $k => $vo) {
                //主单参数节点
                $order_obj = $OrderHead->appendChild($xml->createElement('ceb:' . $k));
                if ($vo != "") {
                    $order_obj->appendChild($xml->createTextNode($vo));
                }
            }

            //创建子单节点
            foreach ($orderlist as $k => $vo) {
                $OrderList = $Order->appendChild($xml->createElement('ceb:InventoryList'));

                foreach ($vo as $p => $q) {
                    //子单参数节点
                    $list_obj = $OrderList->appendChild($xml->createElement('ceb:' . $p));
                    if ($q != "") {
                        $list_obj->appendChild($xml->createTextNode($q));
                    }
                }
            }
        }

        //基础报文传输实体节点
        $BaseTransfer = $ceb->appendChild($xml->createElement('ceb:BaseTransfer'));

        //报文传输的企业代码
        $Base_obj1 = $BaseTransfer->appendChild($xml->createElement('ceb:copCode'));
        $Base_obj1->appendChild($xml->createTextNode($copCode));
        //报文传输的企业名称
        $Base_obj2 = $BaseTransfer->appendChild($xml->createElement('ceb:copName'));
        $Base_obj2->appendChild($xml->createTextNode($copName));
        //默认为DXP；指中国电子口岸数据交换平台
        $Base_obj3 = $BaseTransfer->appendChild($xml->createElement('ceb:dxpMode'));
        $Base_obj3->appendChild($xml->createTextNode($dxpMode));
        //向中国电子口岸数据中心申请数据交换平台的用户编号
        $Base_obj4 = $BaseTransfer->appendChild($xml->createElement('ceb:dxpId'));
        if ($dxpId != "") {
            $Base_obj4->appendChild($xml->createTextNode($dxpId));
        }
        header('Content-type:text/xml;charset=utf-8');
        header('Content-Disposition: attachment; filename="CEB621Message.xml"');
        return $xml->saveXML();
    }

    //下载模板
    public function downTemplate(Request $request)
    {
        $filename = $request->post('name');
        $file = "export/template/{$filename}.xlsx";
        if (is_file($file)) {
            return CatchResponse::success(['url' => 'http://' . $_SERVER['HTTP_HOST'] . '/' . $file]);
        } else {
            return CatchResponse::fail('模板文件不存在');
        }

    }
    //订单导出
    public function exportOrder(Request $request, Excel $excel, orderExport $orderExport){

        $data = $excel->save($orderExport, 'export/orders');
        $data['url'] = str_replace('127.0.0.1:8080','cross.qekj.net',$data['url']);
        return CatchResponse::success($data);
    }
    //订单商品导出
    public function exportOrderGoods(Request $request, Excel $excel, orderGoodsExport $orderGoodsExport){
        $data = $excel->save($orderGoodsExport, 'export/orderList');
        $data['url'] = str_replace('127.0.0.1:8080','cross.qekj.net',$data['url']);
        return CatchResponse::success($data);
    }
    //清单导出
    public function exportClearOrder(Request $request, Excel $excel, clearOrderExport $clearOrderExport){

        return CatchResponse::success($excel->save($clearOrderExport, 'export/orders'));
    }
    //清单商品导出
    public function exportClearOrderGoods(Request $request, Excel $excel, clearOrderGoodsExport $clearOrderGoodsExport){

        return CatchResponse::success($excel->save($clearOrderGoodsExport, 'export/orderList'));
    }
    //清关放行导出
    public function exportFinishClearOrder(Request $request, Excel $excel, clearFinishOrderExport $clearFinishOrderExport){

        return CatchResponse::success($excel->save($clearFinishOrderExport, 'export/orders'));
    }
    //清关放行商品导出
    public function exportFinishClearOrderGoods(Request $request, Excel $excel, clearFinishOrderGoodsExport $clearFinishOrderGoodsExport){

        return CatchResponse::success($excel->save($clearFinishOrderGoodsExport, 'export/orderList'));
    }

    //上传
    public function importLogistics(Request $request)
    {
        // 获取表单上传文件
        $files = request()->file();
        try {
            //10M以下csv,xlsx,xls文件
            validate(['file' => 'fileSize:10485760|fileExt:csv,xlsx,xls'])
                ->check($files);
            $fields = [
                ['field' => 'orderId', 'label' => '订单号'],
                ['field' => 'express_company', 'label' => '快递公司'],
                ['field' => 'express_no', 'label' => '快递单号']
            ];
            $msg = [];
            $this->importExcl(array_column($fields, 'field'), $files['file'], function ($data) use ($fields, &$msg) {
                if (count($data) > 1) {
                    $now = date('Y-m-d H:i:s');
                    // 启动事务
                    Db::startTrans();
                    $success = 0;
                    foreach ($data as $key => $value) {
                        if ($key === 0) {
                            foreach ($fields as $k => $v) {
                                //验证表格头部是否模板字段
                                if (strpos($value[$v['field']], $v['label']) === false) {
                                    $msg = ['code' => 10001, 'message' => '模板表头' . $value[$v['field']] . '不匹配，请下载最新模板'];
                                    Db::rollback();
                                    return;

                                }
                            }
                        } else {
                            $where = [];
                            $params = [];
                            foreach ($fields as $k => $v) {
                                if ($k === 0) {
                                    if (empty($value[$v['field']])) {
                                        $msg = ['code' => 10001, 'message' => '第' . ($key + 1) . '行' . $v['label'] . '不能为空'];
                                        Db::rollback();
                                        return;
                                    }
                                    $where[$v['field']] = $value[$v['field']];
                                } else {
                                    $params[$v['field']] = $value[$v['field']];
                                }
                            }
                            $params['modifyTime'] = $now;
                            $res = Db::table('db_customs_order')->where($where)->save($params);
                            if (!$res) {
                                $msg = ['code' => 10002, 'message' => '第' . ($key + 1) . '行导入失败，请检查订单号'];
                                Db::rollback();
                                return;
                            } else {
                                $success++;
                            }
                        }
                    }
                    if ($success > 0) {
                        Db::commit();
                    } else {
                        Db::rollback();
                    }
                    $msg = ['code' => 10000, 'message' => '操作成功，成功导入' . $success . '条数据'];
                } else {
                    $msg = ['code' => 10002, 'message' => '没有需要导入的数据'];
                }
            });
            if ($msg['code'] === 10000) {
                return CatchResponse::success([], $msg['message']);
            } else {
                return CatchResponse::fail($msg['message']);
            }
        } catch (\think\exception\ValidateException $e) {
            return CatchResponse::fail($e->getMessage());
        }
    }

    /**
     * 导入
     * @param Reader $reader
     * @param $fields
     * @param $file
     * @return bool
     */
    public function importExcl($fields, $file, callable $callable)
    {
        $excel = new class($fields) extends Reader {
            protected $fields;

            public function __construct($fields)
            {
                $this->fields = $fields;
            }

            public function headers()
            {
                // TODO: Implement headers() method.
                return $this->fields;
            }
        };
        $excel->import($file)->then(function ($data) use ($callable) {
            $callable($data);
        });

    }


    /**
     *
     * @time 2021/11/03 14:02
     * sign/msg 生成步骤
     * @param array $content 内容
     * @param string $url 地址
     * @param string $serverCode 服务代码
     * @return string
     */
    public function signMsg($content, $url, $serverCode)
    {
        //sign
        $headcontent = [];
        $head = [];
        $head['serverCode'] = $serverCode;//服务代码
        //$head['companyCode'] = '3201968B31';//企业代码
        $head['companyCode'] = '32016600B1';//企业代码
        $head['timeStamp'] = time();//时间戳
        $head['requestId'] = strtoupper(md5(time(), false)) . rand(1000, 9999);//唯一
        $headcontent['head'] = $head;
        $headcontent['content'] = $content;
        // $key ='qbXJ6i5ig1v0vFJdeFhiZ9IABQykzQVlxhX9J3SZxLZBpgecefNagitkpdo0u7ocmntN8Z3f7z7UftMNGU8lwGWlST2rd75shk6';//测试商户公钥
        //$key = '1hKFmdHyU4pQaohe2dkYnDJv11bq6e7AgkxGcAgpvVyIedksG6DQQdcwanbNqp2O1oLXKAan0a76OdG9c2XpOBR4nJnxTEdRU0r';//生产商户公钥
        $key = 'lFyJDoLmAS4EClok6MDjUmV1AYdBe8LjFW0nquiuo024dxkm6mczUfNsS1UREHfc074pwYA1Tx0igBb0YEAJVvzO7jH0pWe6u7q';
        $headcontent1 = md5(stripslashes(json_encode($headcontent, JSON_UNESCAPED_UNICODE)));
        $sign = md5($headcontent1 . $key);
        //msg
        $msg1 = [];
        $msg1['head'] = $head;
        $msg1['content'] = $content;
        $msg1['sign'] = $sign;
        $msg = base64_encode(json_encode($msg1, JSON_UNESCAPED_UNICODE));
        ///$msg = urlencode(base64_encode(json_encode($msg1)));
        $data['data'] = $msg;
        $info = $this->httprequest($url, $data);
        return $info;
    }

    /**
     *
     * @time 2021/11/03 14:02
     * url请求
     * @param string $url 文件夹类型
     * @param array $data 内容
     * @return string
     */
    protected function httprequest(string $url, array $data)
    {
        $ch = curl_init();//初始化
        //设置请求头信息
        $header = ['Accept-Charset: utf-8'];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

        //curl注意事项，如果发送的请求是https，必须要禁止服务器端校检SSL证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//获取的信息以字符串返回
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     *
     * @time 2021/11/03 14:02
     * 日志
     * @param string $type 文件夹类型
     * @param string $content 内容
     * @return string
     */
    public function writeLog(string $type, string $content)
    {
        $now = date('Y-m-d H:i:s');
        $ip = request()->ip();
        $log_path = 'log/customs/' . $type . '/';
        $destination = $log_path . date('Y-m-d') . '.log';
        if (!is_dir($log_path)) {
            mkdir($log_path, 0755, true);
        }
        error_log("[{$now}] " . $_SERVER['REMOTE_ADDR'] . ' ' . $_SERVER['REQUEST_URI'] . '  IP:' . $ip . "\r\n{$content}\r\n", 3, $destination);
    }


    public function getExportList(){
        $user =(new CatchAuth())->user();

        $where['o.deleted_at'] = 0;
        //非管理员要商户id
        if($user['type'] !== 1 ){
            $where['o.tenant_id'] = $user['tenant_id'];
        }

//        SUM(order_details.quantity * order_details.price) AS total_price')

        return $this->catchSearch()
            ->alias('o')
            ->field("o.orderId,CONCAT(' ',orderId) as orderId2, o.orderDate,o.buyerName,o.ConsigneeCode,o.push_status,
            GROUP_CONCAT(od.order_no) as order_no,
            GROUP_CONCAT(od.goods_spu) AS goods_spu,
            GROUP_CONCAT(od.goods_name SEPARATOR '\n') AS goods_name,
            GROUP_CONCAT(od.sku_id) AS sku_id,
            GROUP_CONCAT(od.deliver_money) AS deliver_money,
            GROUP_CONCAT(od.tenant_total_money) AS tenant_total_money,
            SUM(tenant_total_money) AS total_price")
            ->leftJoin('db_customs_hn_order_detail od','od.order_id = o.id')
            ->where($where)
            ->group('o.id')
            ->select();
    }

}